<!-- 商品标准件结构 -->
<template>
	<div class="app-container">
		<el-row class="mb10">
			<el-col :span="1.5">
				<el-input placeholder="工号/姓名" size="mini" v-model="queryParams.searchValue"></el-input>
			</el-col>
		</el-row>
		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button
					size="mini"
					type="primary" 
					icon="el-icon-search"
					@click="handleQuery"
					v-hasPermi="['system:role:list']">查询</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button
					size="mini"
					type="primary"
					plain
					icon="el-icon-plus"
					@click="handleAdd"
					v-hasPermi="['system:role:add']">新增</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button
					size="mini"
					type="danger"
					plain
					icon="el-icon-delete"
					v-hasPermi="['system:user:admin']"
					@click="handleDelete">删除</el-button>
			</el-col>
		</el-row>
		
		<el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column label="账号" prop="username" width="120"  align="center" />
			<el-table-column label="姓名" prop="name" width="120"  align="center" />
			<el-table-column label="工号" prop="no" width="120"  align="center" />
			<el-table-column label="授权的仓库别" prop="stores" width="120"  align="center" />
			<el-table-column label="是否通用仓别" prop="no" width="100"  align="center">
				<template slot-scope="scope">
					<!-- <span v-if="scope.row.isGeneralStore == 1" style="color: green;">通用</span>
					<span v-if="scope.row.isGeneralStore == 0 || scope.row.isGeneralStore == null" style="color: red;">不通用</span> -->
					<el-switch
						v-model="scope.row.isGeneralStore == 1?true:false" @change="handleChangeIsGeneralStore($event, scope.row.id)"></el-switch>
				</template>
			</el-table-column>
			<el-table-column label="是否可操作" prop="isOperate" width="200"  align="center">
				<template slot-scope="scope">
					<el-switch
						v-model="scope.row.isOperate == 1?true:false" @change="handleChangeOperate($event, scope.row.id)"></el-switch>
				</template>
			</el-table-column>
			<el-table-column label="操作" width="250" align="center">
				<template slot-scope="scope">
					<el-button
					  size="mini"
					  type="text"
					  icon="el-icon-edit"
					  @click="handleUpdate(scope.row)"
					  v-hasPermi="['system:role:edit']"
					>修改</el-button>
					<el-button
						size="mini"
						type="text"
						@click="openResettingPassword(scope.row)">重设密码</el-button>
					<el-button
						size="mini"
						type="text"
						@click="openAuthorizeDialog(scope.row)">授权</el-button>
					<el-button type="text" size="mini" icon="el-icon-delete" v-hasPermi="['system:user:admin']" @click="handleDelete(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		
		<pagination
		  v-show="total > 0"
		  :total="total"
		  :page.sync="queryParams.pageNum"
		  :limit.sync="queryParams.pageSize"
		  @pagination="handleGetList"
		/>
		
		<el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
		  <el-form ref="ruleForm" :model="form" :rules="rules" label-width="90px">
		    <el-row>
				<el-col :span="12">
					<el-form-item label="账号" prop="username">
						<el-input v-model="form.username" placeholder="请输入账号" />
					</el-form-item>
					<el-form-item label="密码" prop="password" v-if="form.id == null">
						<el-input v-model="form.password" placeholder="请输入密码" show-password />
					</el-form-item>
					<el-form-item label="名称" prop="name">
						<el-input v-model="form.name" placeholder="请输入姓名" />
					</el-form-item>
					<el-form-item label="编号" prop="no">
						<el-input v-model="form.no" placeholder="请输入工号" />
					</el-form-item>
					<el-form-item label="授权仓库别" prop="stores">
						<el-input v-model="form.stores" placeholder="请输入仓库别" />
					</el-form-item>
				</el-col>
		    </el-row>
		  </el-form>
		  <div slot="footer" class="dialog-footer">
		    <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
		    <el-button @click="cancel">取 消</el-button>
		  </div>
		</el-dialog>
		
		<!-- 重置密码 begin -->
		<el-dialog :title="resettingPasswordDialogTitle" :visible.sync="resettingPasswordDialogShow" width="600px" append-to-body>
			<el-form ref="resettingPasswordForm" :model="resettingPasswordParams" :rules="resettingPasswordRules" label-width="80px">
				<el-row>
					<el-col :span="12">
						<el-form-item label="输入密码" prop="password">
							<el-input type="password" v-model="resettingPasswordParams.password"></el-input>
						</el-form-item>
						<el-form-item label="确认密码" prop="commitPassword">
							<el-input type="password" v-model="resettingPasswordParams.commitPassword"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="handleResettingPassword">确 定</el-button>
				<el-button @click="resettingPasswordDialogShow = false">取 消</el-button>
			</div>
		</el-dialog>
		<!-- 重置密码 end -->
		
		<!-- 授权 begin -->
		<el-dialog title="授权" :visible.sync="authorizePlantDialogShow" width="500px" append-to-body>
			<div class="authorizeDialog-box">
				<el-checkbox-group v-model="selectedAuthorizePlantList">
					<el-checkbox style="margin-left: 10px;margin-top: 10px;" v-for="(item, index) in authorizePlantList" :label="item.id">{{ item.name }}</el-checkbox>
				</el-checkbox-group>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="handleComitAuthorizePlant">确 定</el-button>
				<el-button @click="authorizePlantDialogShow = false">取 消</el-button>
			</div>
		</el-dialog>
		<!-- 授权 end -->
	</div>
</template>

<script>
	import { queryByPage, insert, update, delByIds, resettingPassword, insertAuthorize, getCustomerPlantListByCustomerId, changeOperate, changeIsGeneralStore } from "@/api/customer/index"
	import { getList } from "@/api/picking/plant"
	import { getToken } from "@/utils/auth"
	export default {
		data() {
			// 判断确认密码和密码是否一致（重置密码功能）begin
			const equalToResettingPassword = (rule, value, callback) => {
			  if (this.resettingPasswordParams.password !== value) {
			    callback(new Error("两次输入的密码不一致"));
			  } else {
			    callback();
			  }
			}
			// 判断确认密码和密码是否一致（重置密码功能）end
			// 判断确认密码和密码是否一致（创建管理员功能）begin
			const createAdminParamsPassword = (rule, value, callback) => {
			  if (this.createAdminParams.password !== value) {
			    callback(new Error("两次输入的密码不一致"));
			  } else {
			    callback();
			  }
			}
			// 判断确认密码和密码是否一致（创建管理员功能）end
			return {
				title: "新增仓管员",
				open: false,
				form: {
					username: "",
					password: "",
					name: "",
					no: "",
					stores: "",
				},
				rules: {
					username: [
						{ required: true, message: "请输入账号", trigger: "blur" },
					],
					password: [
						{ required: true, message: "请输入密码", trigger: "blur" },
					]
				},
				list: [],
				loading: true,
				ids: [],
				total: 0,
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					searchValue: ""
				},
				dateRange:  [],
				
				resettingPasswordDialogTitle: "重置密码",
				resettingPasswordDialogShow: false,
				selectedCustomer: {},
				resettingPasswordParams: {
					password: "",
					commitPassword: ""
				},
				resettingPasswordRules: {
					password: [
						{ required: true, message: "请输入密码", trigger: "blur" },
						// { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
						// { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }
					],
					commitPassword: [
						{ required: true, message: "请输入确认密码", trigger: "blur" },
						{ required: true, validator: equalToResettingPassword, trigger: "blur" }
					],
				},
				
				selectedRow: {},
				// 授权 begin
				authorizePlantDialogShow: false,
				selectedAuthorizePlantList: [],
				authorizePlantList: [],
				// 授权 end
			}
		},
		mounted() {
			let that = this
			that.handleGetList()
			that.handleGetCustomerList()
		},
		methods: {
			async handleChangeOperate(e, id){
				let that = this
				let param = {
					id: id,
					isOperate: e == false?0:1
				}
				let result = await changeOperate(param)
				if(result.code == 200){
					that.handleGetList()
				}
			},
			async handleChangeIsGeneralStore(e, id){
				let that = this
				let param = {
					id: id,
					isGeneralStore: e == false?0:1
				}
				let result = await changeIsGeneralStore(param)
				if(result.code == 200){
					that.handleGetList()
				}
			},
			// 产别授权
			handleComitAuthorizePlant() {
				let that = this
				let selectedAuthorizePlantList = []
				that.selectedAuthorizePlantList.forEach((item, index) => {
					selectedAuthorizePlantList.push(item)
				})
				let param = {
					customerId: that.selectedRow.id,
					plantIds: selectedAuthorizePlantList.join(",")
				}
				insertAuthorize(param).then(res => {
					that.$modal.msgSuccess("授权成功")
					that.authorizePlantDialogShow = false
				}).catch((e) => {
					console.log(e)
				})
			},
			// 查询厂别
			handleGetCustomerList(){
				let that = this
				getList().then(res => {
					if(res.code == 200){
						that.authorizePlantList = res.rows
					}
				}).catch(function() {
				})
			},
			// 打开授权弹框
			openAuthorizeDialog(res) {
				let that = this
				that.selectedRow = res
				that.authorizePlantDialogShow = true
				that.handleGetCustomerPlantListByCustomerId(res)
			},
			// 查询授权的厂别
			handleGetCustomerPlantListByCustomerId(res){
				let that = this
				let param = {
					customerId: res.id
				}
				getCustomerPlantListByCustomerId(param).then(res => {
					let result = res.rows
					let arr = []
					result.forEach((item, index) =>{
						arr.push(item.plantId)
					})
					that.selectedAuthorizePlantList = arr
					that.authorizePlantDialogShow = true
				}).catch((e) => {
					console.log(e)
				})
			},
			// 查询
			handleQuery() {
				let that = this
				that.pageNum = 1
				that.loading = true
				that.handleGetList()
			},
			// 删除
			handleDelete(row) {
				let that = this
				const ids = row.id || that.ids;
				that.$modal.confirm("是否确认删除你选择的仓管员吗？").then(function() {
					delByIds(ids).then(res => {
						that.handleGetList()
						that.$modal.msgSuccess("删除成功");
					}).catch(function() {
					})
				}).catch(() => {
					console.log("删除失败")
				})
			},
			handleGetList() {
				let that = this
				queryByPage(that.addDateRange(that.queryParams, that.dateRange)).then(res => {
					that.list = res.rows
					that.total = res.total
					that.loading = false
				}).catch(function() {
				});
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				let that = this
				that.ids = selection.map(item => item.id)
			},
			// 打开新增
			handleAdd() {
				let that = this
				let form = {
					name: "",
					no: ""
				}
				that.form = form
				that.title = "新增仓管员"
				that.open = true
			},
			handleUpdate(res) {
				let that = this
				let form = {
					id: res.id,
					username: res.username,
					name: res.name,
					no: res.no,
					stores: res.stores
				}
				that.form = form
				that.title = "编辑仓管员"
				that.open = true
			},
			submitForm(formName) {
				let that = this
				that.$refs[formName].validate((valid) => {
					if (valid) {
						if(that.form.id != null) {
							update(that.form).then(res => {
								that.handleGetList()
								that.$modal.msgSuccess("修改成功");
								that.open = false
							}).catch(function() {
							})
						} else {
							insert(that.form).then(res => {
								that.handleGetList()
								that.$modal.msgSuccess("新增成功");
								that.open = false
							}).catch(function() {
							})
						}
					} else {
						return false;
					}
				});
			},
			cancel() {
				let that = this
				that.open = false
			},
			// 打开重置密码弹框
			openResettingPassword(res) {
				let that = this
				that.selectedCustomer = res
				// that.resettingPasswordParams.password = res.password
				that.resettingPasswordDialogShow = true
			},
			// 确认重置密码
			handleResettingPassword() {
				let that = this
				// if(that.resettingPasswordParams.password == null || that.resettingPasswordParams.password == ""){
				// 	that.$modal.msgError("请填写密码");
				// 	return;
				// } else if(that.resettingPasswordParams.commitPassword == null || that.resettingPasswordParams.commitPassword == "") {
				// 	that.$modal.msgError("请填写确认密码");
				// 	return;
				// } else if(that.resettingPasswordParams.commitPassword != that.resettingPasswordParams.password) {
				// 	that.$modal.msgError("密码不一致");
				// 	return
				// }
				that.$refs["resettingPasswordForm"].validate((valid) => {
					if (valid) {
						let params = {
							customId: that.selectedCustomer.id,
							password: that.resettingPasswordParams.password
						}
						resettingPassword(params).then((res) => {
							that.$modal.msgSuccess("设置成功")
							that.resettingPasswordDialogShow = false
						}).catch((e) => {
							console.log(e)
						})
					} else {
						return false;
					}
				})
			},
		}
	}
</script>

<style>
</style>